package cc.smarnet.caihou.phone.deliver;

import android.Manifest;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.smart.command.EscCommand;
import com.smart.command.LabelCommand;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import cc.smarnet.caihou.IPConfig;
import cc.smarnet.caihou.PrintTagActivity;
import cc.smarnet.caihou.R;
import cc.smarnet.caihou.adapter.DeliverAdapter2;
import cc.smarnet.caihou.adapter.SpacesItemDecoration;
import cc.smarnet.caihou.bluetooth.BluetoothDeviceList;
import cc.smarnet.caihou.bluetooth.Constant;
import cc.smarnet.caihou.bluetooth.DeviceConnFactoryManager;
import cc.smarnet.caihou.bluetooth.ThreadPool;
import cc.smarnet.caihou.bluetooth.Utils;
import cc.smarnet.caihou.entity.Deliver;
import cc.smarnet.caihou.entity.FlowerOutorderHZ;
import cc.smarnet.caihou.phone.MainPageActivity;
import cc.smarnet.caihou.util.CommonUtils;
import okhttp3.Call;

/**
* 出库信息的activity----用于打印客户信息标签
* 出库信息的activity----用于打印客户信息标签
* 出库信息的activity----用于打印客户信息标签
* 出库信息的activity----用于打印客户信息标签
* 出库信息的activity----用于打印客户信息标签
* */
public class DeliverActivity2 extends AppCompatActivity {
    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private LinearLayout failLoadLinearLayout;
    private LinearLayout noDataLinearLayout;
    private ProgressBar progressBar;
    private ImageButton imageButton;
    private Button addButton;
    private Button btnSearch;
    private EditText etSearchtext;

    private String token;
    private String orderNo = "";

    private int pageNo = 1;// 取数分页的开始页
    private int pageSize = 10;// 每次取数的数量

    private int printTagNum = 1;// 打印客户标签的数量

    List<Deliver> deliverList = new ArrayList<>();
    DeliverAdapter2 deliverAdapter;



    //蓝牙相关定义：
    private static final String TAG = "PrintTagActivity";
    ArrayList<String> per = new ArrayList<>();

    private int counts;
    private static final int REQUEST_CODE = 0x004;

    private Bitmap bitmap = Bitmap.createBitmap(660, 40, Bitmap.Config.ARGB_8888);

    /**
     * Connection status disconnected
     */
    private static final int CONN_STATE_DISCONN = 0x007;
    /**
     * Use printer command error
     */
    private static final int PRINTER_COMMAND_ERROR = 0x008;

    private static final int CONN_MOST_DEVICES = 0x11;
    private static final int CONN_PRINTER = 0x12;
    private PendingIntent mPermissionIntent;
    private String[] permissions = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH
    };
    private TextView tvConnState;
    private ThreadPool threadPool;

    private int id = 0;
    private int printcount = 0;
    private boolean continuityprint = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deliver2);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        noDataLinearLayout.setVisibility(View.GONE);// 隐藏暂无数据的信息
        failLoadLinearLayout.setVisibility(View.GONE);// 隐藏数据加载失败的信息

        getToken();
        getDeliverInfo();
        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeliverActivity2.this, MainPageActivity.class);
                startActivity(intent);
            }
        });
        // 点击新增按钮的监听
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeliverActivity2.this, DeliverAddActivity.class);
                startActivity(intent);
            }
        });
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局(参数是：上下文、列表方向（横向还是纵向）、是否倒叙)
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new SpacesItemDecoration(20));// 设置item的上下左右边距
        recyclerView.setHasFixedSize(true);
        // 这里使用适配器的目的在于使系统不再报‘E/RecyclerView: No adapter attached; skipping layout’的错误
        /*List<deliver> nullList=new ArrayList<>();
        deliverAdapter=new deliverAdapter(nullList);
        recyclerView.setAdapter(deliverAdapter);*/

        // 下拉刷新，目前在此就不做业务处理了，因为初始时加载的那几条数据就是从第一条开始的查询的
        refreshLayout.setOnRefreshListener(new OnRefreshListener() { //下拉刷新
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh();
            }
        });

        //上拉加载更多
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshlayout) {
                getDeliverInfo();
                refreshlayout.finishLoadMore(0);
            }
        });

        // 搜索按钮监听
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               search();
            }
        });

        tvConnState.setTextColor(Color.parseColor("red"));
    }

    public void initViews() {
        refreshLayout = findViewById(R.id.deliver_refreshLayout);
        recyclerView = findViewById(R.id.deliver_recyclerView);
        failLoadLinearLayout = findViewById(R.id.deliver_failLoad_linearLayout);
        noDataLinearLayout = findViewById(R.id.deliver_noData_linearLayout);
        progressBar = findViewById(R.id.deliver_progressBar);
        imageButton = findViewById(R.id.deliver_return);
        addButton = findViewById(R.id.deliver_add_button);
        btnSearch = findViewById(R.id.btn_search);
        etSearchtext = findViewById(R.id.et_searchtext);
        tvConnState = (TextView) findViewById(R.id.client_printer_button);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }

    public void getDeliverInfo() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + "/flower/flowerOutorder/list";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .addParams("pageNo", String.valueOf(pageNo))
                .addParams("pageSize", String.valueOf(pageSize))
                .addParams("appOrderNo", orderNo)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        failLoadLinearLayout.setVisibility(View.VISIBLE);// 显示数据加载失败的信息
                    }

                    @Override
                    public void onResponse(String response, int ID) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        failLoadLinearLayout.setVisibility(View.GONE);// 隐藏数据加载失败的信息
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            String records = JSON.parseObject(result).getString("records");
//                            JSONArray jsonArray = JSON.parseArray(records);
                            deliverList = JSONArray.parseArray(records, Deliver.class);

                            if (deliverList.size() > 0) {// 如果deliverList中有数据的话就通过deliverAdapter将数据显示在界面上
                                deliverAdapter = new DeliverAdapter2(getApplicationContext(),deliverList);
                                recyclerView.setAdapter(deliverAdapter);


                                deliverAdapter.setOnItemClickListener(new DeliverAdapter2.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(View v, DeliverAdapter2.ViewName viewName, int position) {
                                        switch (v.getId()) {
                                            case R.id.custom_print:
                                                 //开始打印客户标签
                                                printCustom(position);
                                                break;
                                            default:
//                                                Toast.makeText(DeliverActivity2.this, "你点击了item" + (position + 1), Toast.LENGTH_SHORT).show();
                                                break;
                                        }
                                    }

                                    @Override
                                    public void onItemLongClick(View v) {

                                    }
                                });

                            }else {// 否则让暂无数据的信息显示在界面上
                                noDataLinearLayout.setVisibility(View.VISIBLE);
                            }

                            int total=Integer.valueOf(JSON.parseObject(result).getString("total"));//数据在数据库中的总数
                            int current=Integer.valueOf(JSON.parseObject(result).getString("current"));//该次取数是第几次
                            if (current*pageSize>=total){
                                Toast.makeText(DeliverActivity2.this, "已加载完所有数据", Toast.LENGTH_SHORT).show();
                            }

                            pageNo += 1;
                        }
                    }
                });
    }

   public void search(){
       orderNo = etSearchtext.getText().toString();
       if(orderNo==null){
//           CommonUtils.showTotal("请输入搜索单号");
//           return;
           orderNo = "";
       }
       pageNo = 1;
       pageSize = 100;
       deliverList.clear();
       recyclerView.setAdapter(null);
       getDeliverInfo();

   }

    /**
     * Print label  打印标签
     */
    public void printCustom(int index){
        if (!isConnected()) {
            Utils.toast(this, getString(R.string.str_cann_printer));
            return;
        }
        //弹窗，输入标签数量和件数
        setTagNum(index);
    }


    /**
     * Print label
     */
    void sendLabel(int index , int i) {
        Deliver deliver = deliverList.get(index);
        LabelCommand tsc = new LabelCommand();
        // Set the label size according to the actual size
        tsc.addSize(80, 50);
        // Set the label gap according to the actual size. If it is no gap paper, set it to 0
        tsc.addGap(2);
        // Set print direction
        tsc.addDirection(LabelCommand.DIRECTION.BACKWARD, LabelCommand.MIRROR.NORMAL);
        // Turn on Printing with response for continuous printing
        tsc.addQueryPrinterStatus(LabelCommand.RESPONSE_MODE.ON);
        // Set origin coordinates
        tsc.addReference(0, 0);
        // Tearing mode on
        tsc.addTear(EscCommand.ENABLE.ON);
        // Clear print buffer
        tsc.addCls();
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.xdnylogo);
//        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.kunlunlogo);
        tsc.addBitmap(5, 30, -1, 5.0f, LabelCommand.BITMAP_MODE.OVERWRITE, 350, b);

        tsc.addBar(5, 120, 350, 1);
        tsc.addQRCode(410, 30, LabelCommand.EEC.LEVEL_L, 6, LabelCommand.ROTATION.ROTATION_0, deliver.getOrderNo());
        tsc.addText(375, 158, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                deliver.getOrderNo());

        tsc.addText(20, 135, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_2, LabelCommand.FONTMUL.MUL_2,
                 deliver.getUser());

        tsc.addText(20, 195, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_2, LabelCommand.FONTMUL.MUL_2,
                deliver.getTouser()+"(收)");
        tsc.addText(20, 265, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_2, LabelCommand.FONTMUL.MUL_2,
                usedPhone(deliver.getTophone()));

//        tsc.addText(20, 315, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
//                deliver.getRemarks());
        tsc.addText(350, 265, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_2, LabelCommand.FONTMUL.MUL_2,
                i +"/" + printTagNum+"件");

        String address = "";
        if(StringUtils.isNotBlank( deliver.getAddress())){
            address = deliver.getAddress() ;
        }
        tsc.addText(20, 325, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                 address);

        SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //格式化当前系统日期
        String dateTime = dateFm.format(new java.util.Date());
        tsc.addText(20, 355, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                "打印时间：" + dateTime);

        // print label
        tsc.addPrint(1, 1);
        // Buzzer sounds after label printing
        tsc.addSound(2, 100);
        tsc.addCashdrwer(LabelCommand.FOOT.F5, 255, 255);
        Vector<Byte> datas = tsc.getCommand();
        // send data
        DeviceConnFactoryManager.getDeviceConnFactoryManager().sendDataImmediately(datas);
    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE);
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);
        registerReceiver(receiver22, filter);
    }

    private void checkPermission() {
        for (String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, permission)) {
                per.add(permission);
            }
        }
    }

    private void requestPermission() {
        if (per.size() > 0) {
            String[] p = new String[per.size()];
            ActivityCompat.requestPermissions(this, per.toArray(p), REQUEST_CODE);
        }
    }

    /**
     * Bluetooth connect
     */
    public void btnBluetoothConnCoust(View view) {
        startActivityForResult(new Intent(this, BluetoothDeviceList.class), Constant.BLUETOOTH_REQUEST_CODE);
    }

    /**
     * Disconnect
     */
    public void btnDisConn(View view) {
        if (!isConnected()) {
            Utils.toast(this, getString(R.string.str_cann_printer));
            return;
        }
        mHandler.obtainMessage(CONN_STATE_DISCONN).sendToTarget();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case Constant.BLUETOOTH_REQUEST_CODE: {
                    closeport();
                    //Get bluetoot mac address
                    String macAddress = data.getStringExtra(BluetoothDeviceList.EXTRA_DEVICE_ADDRESS);
                    //Init DeviceConnFactoryManager
                    new DeviceConnFactoryManager.Build()
                            .setConnectMethod(DeviceConnFactoryManager.CONN_METHOD.BLUETOOTH)
                            //Set bluetooth mac address
                            .setMacAddress(macAddress)
                            .build();
                    //Open port
                    threadPool = ThreadPool.getInstantiation();
                    threadPool.addTask(() -> DeviceConnFactoryManager.getDeviceConnFactoryManager().openPort());

                    break;
                }
                default:
                    break;
            }
        }
    }




    private BroadcastReceiver receiver22 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case DeviceConnFactoryManager.ACTION_CONN_STATE:
                    int state = intent.getIntExtra(DeviceConnFactoryManager.STATE, -1);
                    int deviceId = intent.getIntExtra(DeviceConnFactoryManager.DEVICE_ID, -1);
                    switch (state) {
                        case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:
                            if (id == deviceId) {
                                tvConnState.setText(getString(R.string.str_conn_state_disconnect));
                                tvConnState.setTextColor(Color.parseColor("red"));
                            }
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTING:
                            tvConnState.setText(getString(R.string.str_conn_state_connecting));
                            tvConnState.setTextColor(Color.parseColor("red"));
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                            tvConnState.setText(getString(R.string.str_conn_state_connected) + "\n" + getConnDeviceInfo());
                            tvConnState.setBackgroundColor(Color.parseColor("#CCFFCC"));
                            tvConnState.setTextColor(Color.parseColor("green"));
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_FAILED:
                            Utils.toast(DeliverActivity2.this, getString(R.string.str_conn_fail));
                            //wificonn=false;
                            tvConnState.setText(getString(R.string.str_conn_state_disconnect));
                            tvConnState.setTextColor(Color.parseColor("red"));
                            break;
                        default:
                            break;
                    }
                    break;
                case DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE:
                    if (counts >= 0) {
                        if (continuityprint) {
                            printcount++;
                            Utils.toast(DeliverActivity2.this, getString(R.string.str_continuityprinter) + " " + printcount);
                        }
                        if (counts != 0) {
//                            sendContinuityPrint();
                        } else {
                            continuityprint = false;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * Reconnection recycles the last connected object to avoid memory leakage
     */
    private void closeport() {
        if (isConnected()) {
//            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].reader.cancel();
            DeviceConnFactoryManager.getDeviceConnFactoryManager().closePort();
        }
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONN_STATE_DISCONN:
                    if (isConnected()) {
                        DeviceConnFactoryManager.getDeviceConnFactoryManager().closePort();
                        Utils.toast(DeliverActivity2.this, getString(R.string.str_disconnect_success));
                    }
                    break;
                case PRINTER_COMMAND_ERROR:
                    Utils.toast(DeliverActivity2.this, getString(R.string.str_choice_printer_command));
                    break;
                case CONN_PRINTER:
                    Utils.toast(DeliverActivity2.this, getString(R.string.str_cann_printer));
                    break;
            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiver22);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.e(TAG, "onDestroy()");
//        if (isConnected()) {
//            DeviceConnFactoryManager.getDeviceConnFactoryManager().closePort();
//        }

//        if (threadPool != null) {
//            threadPool.stopThreadPool();
//        }
        if (!isConnected()) {
            Utils.toast(this, getString(R.string.str_cann_printer));
            return;
        }
        mHandler.obtainMessage(CONN_STATE_DISCONN).sendToTarget();

    }

    private String getConnDeviceInfo() {
        String str = "";
        if (isConnected()) {
            if (DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnMethod() == DeviceConnFactoryManager.CONN_METHOD.BLUETOOTH) {
//                str += "BLUETOOTH\n";
                str += "名称: " + DeviceConnFactoryManager.getDeviceConnFactoryManager().getMacAddress();
            } else if (DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnMethod() == DeviceConnFactoryManager.CONN_METHOD.WIFI) {
                str += "WIFI\n";
                str += "IP: " + DeviceConnFactoryManager.getDeviceConnFactoryManager().getIp() + "\n";
                str += "Port: " + DeviceConnFactoryManager.getDeviceConnFactoryManager().getPort();
            }
        }
        return str;
    }

    private boolean isConnected() {
        return DeviceConnFactoryManager.getDeviceConnFactoryManager() != null && DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnState();
    }
    private String usedPhone(String phone) {
        String usedPhone  = "";
        if(StringUtils.isNotBlank(phone)) {
            usedPhone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        }
        return usedPhone;
    }

    private void setTagNum(int index ) {
        final EditText inputServer = new EditText(this);
        inputServer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("输入客户标签数量").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer)
                .setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String _sign = inputServer.getText().toString();
                if (_sign != null && !_sign.isEmpty()) {
                    printTagNum = Integer.valueOf(_sign) ;
                    Toast.makeText(DeliverActivity2.this, "开始打印客户标签" , Toast.LENGTH_SHORT).show();
                    threadPool = ThreadPool.getInstantiation();
                    threadPool.addTask(() -> {
                        if (!isConnected()) {
                            mHandler.obtainMessage(CONN_PRINTER).sendToTarget();
                            return;
                        }
                        for( int i = 1 ; i<= printTagNum ; i++){
                            sendLabel(index, i);
                        }
                    });
                } else {
                    Toast.makeText(DeliverActivity2.this, "客户标签数量为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.show();
    }
}